package com.scoring.system.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.scoring.system.annotation.SkipSecurityCheck;
import com.scoring.system.pojo.Achievement;
import com.scoring.system.pojo.ClassCurriculum;
import com.scoring.system.pojo.Classes;
import com.scoring.system.pojo.Colleage;
import com.scoring.system.pojo.Course;
import com.scoring.system.pojo.ExpandQuality;
import com.scoring.system.pojo.Major;
import com.scoring.system.pojo.MoralAchievement;
import com.scoring.system.pojo.Student;
import com.scoring.system.pojo.Term;
import com.scoring.system.pojo.User;
import com.scoring.system.service.AchievementService;
import com.scoring.system.service.ClassCurriculumService;
import com.scoring.system.service.ClassesService;
import com.scoring.system.service.ColleageService;
import com.scoring.system.service.CourseService;
import com.scoring.system.service.ExpandQualityService;
import com.scoring.system.service.MajorService;
import com.scoring.system.service.MoralAchievementService;
import com.scoring.system.service.StudentService;
import com.scoring.system.service.TermSerivce;
import com.scoring.system.service.UserService;

@Controller
@RequestMapping("/scorePromoter")
public class ScorePromoterController {
	private static Logger logger = Logger.getLogger(AdminController.class);
	private Map<String, Object> map;

	@Autowired
	private UserService userService;

	@Autowired
	private StudentService studentService;

	@Autowired
	private ColleageService colleageService;

	@Autowired
	private MajorService majorService;

	@Autowired
	private ClassesService classesService;

	@Autowired
	private TermSerivce termSerivce;

	@Autowired
	private CourseService courseService;

	@Autowired
	private AchievementService achievementService;
	
	@Autowired
	private ClassCurriculumService classCurriCulumService;
	
	@Autowired
	private ExpandQualityService expandQualityService;
	
	@Autowired
	private MoralAchievementService moralAchievementService;

	@RequestMapping("getScorePromoter")
	@SkipSecurityCheck
	@ResponseBody
	public Map getScorePromoter(HttpServletRequest request, ModelMap modelMap) {
		HttpSession se = request.getSession();
		User scorePromoter = (User) se.getAttribute("user");
		logger.info("get scorePromoter[" + scorePromoter + "]");
		map = new HashMap();
		map.put("scorePromoter", scorePromoter);
		return map;
	}

	@RequestMapping("updateScorePromoterMessage")
	@SkipSecurityCheck
	@ResponseBody
	public Map updateScorePromoterMeassge(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		User scorePromoter = (User) se.getAttribute("user");
		String userId = request.getParameter("user_id");
		String mailbox = request.getParameter("mailbox");
		String phone = request.getParameter("phone");
		logger.info("get scorePromoterMessage[" + "userId=" + userId + ",mailbox=" + mailbox + ",phone=" + phone + "]");
		if (!userId.equals(scorePromoter.getUserNumber())) {
			map.put("isSame", "no");
		} else {
			scorePromoter.setMailbox(mailbox);
			scorePromoter.setPhone(phone);
			int count = userService.updateUser(scorePromoter);
			if (count > 0) {
				map.put("update", "success");
			} else {
				map.put("update", "failed");
			}
		}
		return map;
	}

	@RequestMapping("updateScorePromoterPassword")
	@SkipSecurityCheck
	@ResponseBody
	public Map updatePssword(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String oldPassword = request.getParameter("old_password");
		String newPassword = request.getParameter("new_password");
		String confrimPassword = request.getParameter("confirm_password");
		logger.info("get scorePromoterPassword:old_password" + oldPassword + ",new_password=" + newPassword
				+ ",confirm_password=" + confrimPassword);
		HttpSession se = request.getSession();
		User scorePromoter = (User) se.getAttribute("user");
		if (!oldPassword.equals(scorePromoter.getPassword())) {
			map.put("isExsit", "false");
		} else if (!newPassword.equals(confrimPassword)) {
			map.put("equal", "false");
		} else {
			scorePromoter.setPassword(newPassword);
			int count = userService.updateUser(scorePromoter);
			if (count > 0) {
				map.put("update", "success");
			} else {
				map.put("update", "false");
			}
		}
		return map;
	}

	@RequestMapping("listColleage")
	@SkipSecurityCheck
	@ResponseBody
	public Map listColleage(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		List<Colleage> colleages = new ArrayList<>();
		List<Colleage> colleage = colleageService.listColleage();
		for (Colleage co : colleage) {
			logger.info("get colleage:" + co);
			colleages.add(co);
		}
		map.put("colleage", colleages);
		return map;

	}

	@RequestMapping("listMajorByColleage")
	@SkipSecurityCheck
	@ResponseBody
	public Map listMajorByColleage(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String colleage = request.getParameter("colleage");
		Colleage co = colleageService.getColleageByName(colleage);
		List<Major> majors = new ArrayList<>();
		List<Major> major = majorService.listMajorByColleageId(co.getId());
		for (Major ma : major) {
			logger.info("get major:" + ma);
			majors.add(ma);
		}
		map.put("major", majors);
		return map;
	}

	@RequestMapping("listClassByMajor")
	@SkipSecurityCheck
	@ResponseBody
	public Map listClassByMajor(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		String major = request.getParameter("major");
		Major ma = majorService.gerMajorByName(major);
		List<Classes> classes = new ArrayList<>();
		List<Classes> clazz = classesService.listClassByMajorId(ma.getId());
		for (Classes cla : clazz) {
			logger.info("get class:" + cla);
			classes.add(cla);
		}
		map.put("classes", classes);
		return map;
	}
	@RequestMapping("listTermByClass")
	@SkipSecurityCheck
	@ResponseBody
	public Map listTermByClass(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		String clazz = request.getParameter("class_name");
		int index= clazz.indexOf("2");
		int year =Integer.valueOf(clazz.substring(index,index+4));
		List<Term> term =new ArrayList<>();
		List<Term> terms =termSerivce.listTerm();
		for(Term te : terms ){
			logger.info("get term:"+te);
			int index1=te.getName().indexOf("-");
			int year1=Integer.valueOf(te.getName().substring(0, index1));
			if(year-year1>=0||year-year1>=-3){
				term.add(te);
			}
		}
		map.put("term", term);
		return map;
	}
	@RequestMapping("listCourseByClassAndTerm")
	@SkipSecurityCheck
	@ResponseBody
	public Map listCourseByClassAndTerm(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		String clazz = request.getParameter("class_name");
		String term = request.getParameter("term");
		logger.info("get class="+clazz+",term="+term);
		Classes cla =classesService.getClassByName(clazz);
		List<String> course =new ArrayList<>();
		List<ClassCurriculum> classCurriculums =classCurriCulumService.listClassCurriculumByClassIdAndTerm(cla.getId(), term);
		for(ClassCurriculum cc : classCurriculums ){
			if(cc.getIsDeleted()!=true){
				logger.info("get classCurriculum:"+cc);
				course.add(cc.getCourse().getName());
			}
		}
		map.put("course", course);
		return map;
	}

	@RequestMapping("listExpandQualityByClass")
	@SkipSecurityCheck
	@ResponseBody
	public Map listExpandQualityByClass(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		String clazz = request.getParameter("class_name");
		Classes cla = classesService.getClassByName(clazz);
		se.setAttribute("classId", cla.getId());
		List<Student> students =studentService.listStudentByClassId(cla.getId());
		List<Student> student=new ArrayList<>();
		for(Student stu:students){
			if(stu.getIsDeleted()!=true){
				student.add(stu);
			}
		}
		logger.info("get student="+student);
		List<ExpandQuality> expandQuality = new ArrayList<>();
		List<ExpandQuality> expandQualities = expandQualityService.listExpandQualityByClass(cla.getId());
		for (ExpandQuality eq : expandQualities) {
				logger.info("get expandQuality="+eq);
				expandQuality.add(eq);
				int studentId =eq.getStudentId();
				logger.info("get studentId="+studentId);
				Student st=studentService.getStudentById(studentId);
				logger.info("get st="+st);
				int index=student.indexOf(st);
				logger.info("get index="+index);
				student.remove(index);
			}
		map.put("student", student);
		map.put("expandQuality", expandQuality);
		return map;
	}
	@RequestMapping("listMoralAchievementByClass")
	@SkipSecurityCheck
	@ResponseBody
	public Map listMoralAchievementByClass(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		String clazz = request.getParameter("class_name");
		Classes cla = classesService.getClassByName(clazz);
		se.setAttribute("classId", cla.getId());
		List<Student> students =studentService.listStudentByClassId(cla.getId());
		List<Student> student=new ArrayList<>();
		for(Student stu:students){
			if(stu.getIsDeleted()!=true){
				student.add(stu);
			}
		}
		logger.info("get student="+student);
		List<MoralAchievement> moralAchievement = new ArrayList<>();
		List<MoralAchievement> moralAchievements = moralAchievementService.listMoralAchievementByClass(cla.getId());
		for (MoralAchievement ma : moralAchievements) {
			    logger.info("get moralAchievement:" + ma);
			    moralAchievement.add(ma);
				int studentId =ma.getStudentId();
				logger.info("get studentId="+studentId);
				Student st=studentService.getStudentById(studentId);
				logger.info("get st="+st);
				int index=student.indexOf(st);
				logger.info("get index="+index);
				student.remove(index);
		}
		map.put("student", student);
		map.put("virtue", moralAchievement);
		return map;
	}
	@RequestMapping("listAchievementByClassAndTermAndCourse")
	@SkipSecurityCheck
	@ResponseBody
	public Map listAchievementByClassAndTermAndCourse(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		String clazz = request.getParameter("class_name");
		String term = request.getParameter("term");
		String course = request.getParameter("course_name");
		Classes cla = classesService.getClassByName(clazz);
		Course cour = courseService.getCourseByName(course);
		logger.info("get cla="+cla+",cour="+cour);
		se.setAttribute("classId", cla.getId());
		se.setAttribute("courseId", cour.getId());
		List<Student> students =studentService.listStudentByClassId(cla.getId());
		List<Student> student=new ArrayList<>();
		for(Student stu:students){
			if(stu.getIsDeleted()!=true){
				student.add(stu);
			}
		}
		logger.info("get students="+students);
		List<Achievement> achievement = new ArrayList<>();
		List<Achievement> achievements = achievementService.listAchievementByClassIdAndTermAndCourseId(cla.getId(), term, cour.getId());
		for (Achievement ach : achievements) {
			logger.info("get achievement:" + ach);
			if (ach.getIsDeleted() != true) {
				achievement.add(ach);
				int studentId =ach.getStudentId();
				logger.info("get studentId="+studentId);
				Student st=studentService.getStudentById(studentId);
				logger.info("get st="+st);
				int index=student.indexOf(st);
				logger.info("get index="+index);
				student.remove(index);
		}
	}
		map.put("student", student);
		map.put("achievement", achievement);
		return map;
	}

	@RequestMapping("listStudentByClass")
	@SkipSecurityCheck
	@ResponseBody
	public Map listStudentByClass(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		String clazz = request.getParameter("class_name");
		Classes cla = classesService.getClassByName(clazz);
		se.setAttribute("classId", cla.getId());
		List<Student> student = new ArrayList<>();
		List<Student> students = studentService.listStudentByClassId(cla.getId());
		for (Student stu : students) {
			logger.info("get student:" + stu);
			if (stu.getIsDeleted() != true) {
				student.add(stu);
			}
		}
		map.put("student", student);
		return map;
	}

	@RequestMapping("createMoralAchievement")
	@SkipSecurityCheck
	@ResponseBody
	public Map createMoralAchievement(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		String studentId = request.getParameter("student_id");
		Student stu =studentService.getStudentByStudentNumber(studentId);
		MoralAchievement ma=moralAchievementService.getMoralAcievementByStudent(Integer.valueOf(stu.getId()));
		logger.info("get moralAchievement="+ma);
		if(ma!=null){
			map.put("isExsit", "yes");
		}else{
			String score = request.getParameter("score");
			String score1 = request.getParameter("score1");
			String score2 = request.getParameter("score2");
			double score3 = 0;
			int classId = (int) (se.getAttribute("classId"));
			logger.info("get studentId =" + studentId + " ,score=" + score+",score1="+score1+",score2="+score2);
			score3=(Double.valueOf(score)*0.3)+(Double.valueOf(score1)*0.3)+(Double.valueOf(score2)*0.4);
			logger.info("get score3 = "+score3);
			Student student = studentService.getStudentByStudentNumber(studentId);
			MoralAchievement  moralAchievement = new MoralAchievement();
			moralAchievement.setClassId(classId);
			moralAchievement.setStudentId(student.getId());
			moralAchievement.setScore(score);
			moralAchievement.setTeacherScore(score1);
			moralAchievement.setGroupScore(score2);
			moralAchievement.setTotalScore(String.valueOf((int)score3));
			int count = moralAchievementService.saveMoralAchievement(moralAchievement);
			if (count > 0) {
				map.put("success", "true");
			} else {
				map.put("success", "false");
			}
		}
		return map;
	}

	@RequestMapping("createExpandQuality")
	@SkipSecurityCheck
	@ResponseBody
	public Map createExpandQuality(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		String studentId = request.getParameter("student_id");
		Student stu =studentService.getStudentByStudentNumber(studentId);
		ExpandQuality eq =expandQualityService.getExpandQualityByStduent(Integer.valueOf(stu.getId()));
		if(eq!=null){
			map.put("isExsit", "yes");
		}else{
			String score = request.getParameter("score");
			String score1 = request.getParameter("score1");
			String score2 = request.getParameter("score2");
			String score3 = request.getParameter("score3");
			String score4="0";
			int classId = (int) (se.getAttribute("classId"));
			logger.info("get studentId =" + studentId + " ,score=" + score+",score1="+score1+"score2="+score2+"score3="+score3);
			score4=String.valueOf(Integer.valueOf(score)+Integer.valueOf(score1)+Integer.valueOf(score2)+Integer.valueOf(score3));
			logger.info("get score4="+score4);
			Student student = studentService.getStudentByStudentNumber(studentId);
			ExpandQuality expandQuality = new ExpandQuality();
			expandQuality.setClassId(classId);
			expandQuality.setStudentId(student.getId());
			expandQuality.setInnovationCreativity(score);
			expandQuality.setPracticalAbility(score1);
			expandQuality.setManagementAbility(score2);
			expandQuality.setSportsAchievement(score3);
			expandQuality.setTotalScore(score4);
			int count = expandQualityService.saveExpandQuality(expandQuality);
			if (count > 0) {
				map.put("success", "true");
			} else {
				map.put("success", "false");
			}
		}
		return map;
	}
	@RequestMapping("createAchievement")
	@SkipSecurityCheck
	@ResponseBody
	public Map createAchievement(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		HttpSession se = request.getSession();
		String studentId = request.getParameter("student_id");
		String score = request.getParameter("score");
		String term = request.getParameter("term");
		int classId = (int) (se.getAttribute("classId"));
		int courseId = (int) (se.getAttribute("courseId"));
		logger.info("get studentId =" + studentId + " ,score=" + score+",term="+term);
		Student student = studentService.getStudentByStudentNumber(studentId);
		Achievement ac=achievementService.getAchievementByStudentIdAndCourseId(student.getId(), courseId);
		if(ac!=null){
			map.put("isExsit", "yes");
		}else{
			Achievement achievement = new Achievement();
			achievement.setClassId(classId);
			achievement.setStudentId(student.getId());
			achievement.setCourseId(courseId);
			achievement.setScore(score);
			achievement.setTerm(term);
			achievement.setType("智");
			achievement.setIsDeleted(false);
			int count = achievementService.saveAchievement(achievement);
			if (count > 0) {
				map.put("success", "true");
			} else {
				map.put("success", "false");
			}
		}
		return map;
	}

	@RequestMapping("getAchievement")
	@SkipSecurityCheck
	@ResponseBody
	public Map getAchievement(HttpServletRequest request, ModelMap modelMap) {
		HttpSession se = request.getSession();
		map = new HashMap();
		int achievementId = Integer.valueOf(request.getParameter("id"));
		logger.info("get achievementId=" + achievementId);
		Achievement achievement = achievementService.getAchievementById(achievementId);
		logger.info("get achievement:" + achievement);
		se.setAttribute("achievement", achievement);
		map.put("achievement", achievement);
		return map;

	}
	@RequestMapping("getExpandQuality")
	@SkipSecurityCheck
	@ResponseBody
	public Map getExpandQuality(HttpServletRequest request, ModelMap modelMap) {
		HttpSession se = request.getSession();
		map = new HashMap();
		int expandQualityId = Integer.valueOf(request.getParameter("id"));
		logger.info("get expandQualityId=" + expandQualityId);
		ExpandQuality expandQuality =expandQualityService.getExpandQualityById(expandQualityId);
		logger.info("get expandQuality:" + expandQuality);
		se.setAttribute("expandQuality", expandQuality);
		map.put("expandQuality", expandQuality);
		return map;
		
	}
	@RequestMapping("getMoralAchievement")
	@SkipSecurityCheck
	@ResponseBody
	public Map getMoralAchievement(HttpServletRequest request, ModelMap modelMap) {
		HttpSession se = request.getSession();
		map = new HashMap();
		int moralAchievementId = Integer.valueOf(request.getParameter("id"));
		logger.info("get moralAchievementId=" + moralAchievementId);
		MoralAchievement moralAchievement = moralAchievementService.getMoralAcievementById(moralAchievementId);
		logger.info("get moralAchievement:" + moralAchievement);
		se.setAttribute("moralAchievement", moralAchievement);
		map.put("moralAchievement", moralAchievement);
		return map;
		
	}

	@RequestMapping("deleteAchievement")
	@SkipSecurityCheck
	@ResponseBody
	public Map deleteAchievement(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		int achievementId = Integer.valueOf(request.getParameter("id"));
		logger.info("get achievementId=" + achievementId);
		Achievement achievement = achievementService.getAchievementById(achievementId);
		logger.info("get achievement:" + achievement);
		int count = achievementService.softDelete(achievementId);
		if (count > 0) {
			map.put("isDelete", "true");
		} else {
			map.put("isDelete", "failed");
		}
		return map;

	}
	@RequestMapping("deleteExpandQuality")
	@SkipSecurityCheck
	@ResponseBody
	public Map deleteExpandQuality(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		int expandQualityId = Integer.valueOf(request.getParameter("id"));
		logger.info("get expandQualityId=" + expandQualityId);
		ExpandQuality expandQuality =expandQualityService.getExpandQualityById(expandQualityId);
		logger.info("get expandQuality:" + expandQuality);
		int count =expandQualityService.deleteById(expandQuality.getId());
		if (count > 0) {
			map.put("isDelete", "true");
		} else {
			map.put("isDelete", "failed");
		}
		return map;
		
	}
	@RequestMapping("deleteMoralAchievement")
	@SkipSecurityCheck
	@ResponseBody
	public Map deleteMoralAchievement(HttpServletRequest request, ModelMap modelMap) {
		map = new HashMap();
		int moralAchievementId = Integer.valueOf(request.getParameter("id"));
		logger.info("get moralAchievementId=" + moralAchievementId);
		MoralAchievement moralAchievement = moralAchievementService.getMoralAcievementById(moralAchievementId);
		logger.info("get moralAchievement:" + moralAchievement);
		int count = moralAchievementService.deleteById(moralAchievementId);
		if (count > 0) {
			map.put("isDelete", "true");
		} else {
			map.put("isDelete", "failed");
		}
		return map;
		
	}

	@RequestMapping("updateAchievement")
	@SkipSecurityCheck
	@ResponseBody
	public Map updateAchievement(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		HttpSession se = request.getSession();
		String score = request.getParameter("score");
		Achievement achievement =(Achievement)se.getAttribute("achievement");
		logger.info("get score"+score);
		achievement.setScore(score);
		int count = achievementService.updateAchievement(achievement);
		if(count>0){
			map.put("update", "true");
		}else{
			map.put("update", "false");
		}
	    return map;
    }
	@RequestMapping("updateExpandQuality")
	@SkipSecurityCheck
	@ResponseBody
	public Map updateExpandQuality(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		HttpSession se = request.getSession();
		String score = request.getParameter("score");
		String score1 = request.getParameter("score1");
		String score2 = request.getParameter("score2");
		String score3 = request.getParameter("score3");
		String score4="0";
		logger.info("get score=" + score+",score1="+score1+"score2="+score2+"score3="+score3);
		score4=String.valueOf(Integer.valueOf(score)+Integer.valueOf(score1)+Integer.valueOf(score2)+Integer.valueOf(score3));
		logger.info("get score4="+score4);
		ExpandQuality expandQuality =(ExpandQuality)se.getAttribute("expandQuality");
		logger.info("get expandQuality="+expandQuality);
		expandQuality.setInnovationCreativity(score);
		expandQuality.setPracticalAbility(score1);
		expandQuality.setManagementAbility(score2);
		expandQuality.setSportsAchievement(score3);
		expandQuality.setTotalScore(score4);
		int count = expandQualityService.updateExpandQuality(expandQuality);
		if(count>0){
			map.put("update", "true");
		}else{
			map.put("update", "false");
		}
		return map;
	}
	@RequestMapping("updateMoralAchievement")
	@SkipSecurityCheck
	@ResponseBody
	public Map updateMoralAchievement(HttpServletRequest request, ModelMap modelMap){
		map = new HashMap();
		HttpSession se = request.getSession();
		String score = request.getParameter("score");
		String score1 = request.getParameter("score1");
		String score2 = request.getParameter("score2");
		double score3 = 0;
		int classId = (int) (se.getAttribute("classId"));
		logger.info("get  score=" + score+",score1="+score1+",score2="+score2);
		score3=(Double.valueOf(score)*0.3)+(Double.valueOf(score1)*0.3)+(Double.valueOf(score2)*0.4);
		logger.info("get score3 = "+score3);
		MoralAchievement moralAchievement =(MoralAchievement)se.getAttribute("moralAchievement");
		logger.info("get moralAchievement="+moralAchievement);
		moralAchievement.setScore(score);
		moralAchievement.setTeacherScore(score1);
		moralAchievement.setGroupScore(score2);
		moralAchievement.setTotalScore(String.valueOf((int)score3));
		int count = moralAchievementService.updateMoralAchievement(moralAchievement);
		if(count>0){
			map.put("update", "true");
		}else{
			map.put("update", "false");
		}
		return map;
	}
	@RequestMapping("importMoralAchievement")
	@SkipSecurityCheck
	@ResponseBody
	public Map importMoralAchievement(/*@RequestParam(value = "file", required = false) MultipartFile file,*/
			HttpServletRequest request, ModelMap modelMap) throws FileUploadException{
		map = new HashMap();
		String savePath=request.getSession().getServletContext().getRealPath("upload");
		String tempPath=request.getSession().getServletContext().getRealPath("upload1");
        String fe=uploadFile(request);
        String fileName=fe.substring(1, fe.length()-1);
        logger.info("get fileName="+fileName);
        if("".equals(fileName)){
        	map.put("upload", "filed");
        }else{
        	File f =new File(savePath,fileName);
        	try {
				List<List<Object>> lists=readExcel(f);
				int i=0,success=0,error=0;
				for(List<Object> list:lists){
					if(i++==0) continue;//表头不取
					if(list==null||list.size()==0) break;//读取到空结束
					Student stu = studentService.getStudentByStudentNumber(list.get(1).toString().replace(".00", ""));
					Classes clazz=classesService.getClassByName(list.get(0).toString());
					logger.info("get stu ="+stu +",class="+clazz);
					MoralAchievement ma =moralAchievementService.getMoralAcievementByStudent(stu.getId());
					if(ma==null){
						MoralAchievement  mat =new MoralAchievement();
						mat.setClassId(clazz.getId());
						mat.setStudentId(stu.getId());
						mat.setScore(list.get(3).toString().replace(".00", ""));
						mat.setTeacherScore(list.get(4).toString().replace(".00", ""));
						mat.setGroupScore(list.get(5).toString().replace(".00", ""));
						double score1=Double.valueOf(list.get(3).toString().replace(".00", ""));
						double score2=Double.valueOf(list.get(4).toString().replace(".00", ""));
						double score3=Double.valueOf(list.get(5).toString().replace(".00", ""));
						String totalScore =String.valueOf((int)(score1*0.3+score2*0.3+score3*0.4));
						mat.setTotalScore(totalScore);
						logger.info("get classId="+clazz.getId()+",studentId="+stu.getId()+",score1="+score1+
								",score2="+score2+",score3="+score3+",totalScore="+totalScore);
						int count=moralAchievementService.saveMoralAchievement(mat);
						if(count>0){
							success++;
						}else{
							error++;
						}
					}else{
						ma.setScore(list.get(3).toString());
						ma.setTeacherScore(list.get(4).toString());
						ma.setGroupScore(list.get(5).toString());
						double score1=Double.valueOf(list.get(3).toString());
						double score2=Double.valueOf(list.get(4).toString());
						double score3=Double.valueOf(list.get(5).toString());
						String totalScore =String.valueOf((int)(score1*0.3+score2*0.3+score3*0.4));
						ma.setTotalScore(totalScore);
						int count=moralAchievementService.updateMoralAchievement(ma);
						if(count>0){
							success++;
						}else{
							error++;
						}
					}
					map.put("success", success);
					map.put("error", error);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
		return map;
	}
	@RequestMapping("importAchievement")
	@SkipSecurityCheck
	@ResponseBody
	public Map importAchievement(HttpServletRequest request, ModelMap modelMap) throws FileUploadException{
		map = new HashMap();
		String savePath=request.getSession().getServletContext().getRealPath("upload");
		String tempPath=request.getSession().getServletContext().getRealPath("upload1");
		String fe=uploadFile(request);
		String fileName=fe.substring(1, fe.length()-1);
		logger.info("get fileName="+fileName);
		if("".equals(fileName)){
			map.put("upload", "filed");
		}else{
			File f =new File(savePath,fileName);
			try {
				List<List<Object>> lists=readExcel(f);
				int i=0,success=0,error=0;
				for(List<Object> list:lists){
					if(i++==0) continue;//表头不取
					if(list==null||list.size()==0) break;//读取到空结束
					Student stu = studentService.getStudentByStudentNumber(list.get(2).toString().replace(".00", ""));
					Classes clazz=classesService.getClassByName(list.get(1).toString());
					String term =list.get(0).toString();
					String score=list.get(5).toString().replace(".00", "");
					Course course = courseService.getCourseByName(list.get(4).toString());
					logger.info("get stu ="+stu.getName() +",class="+clazz.getName()+",term="+term+"course="+course.getName()+",score="+score);
					Achievement ac =achievementService.getAchievementByStudentIdAndCourseId(stu.getId(), course.getId());
					if(ac==null){
						Achievement  achievement =new Achievement();
						achievement.setClassId(clazz.getId());
						achievement.setStudentId(stu.getId());
						achievement.setCourseId(course.getId());
						achievement.setScore(score);
						achievement.setTerm(term);
						achievement.setType("智");
						int count=achievementService.saveAchievement(achievement);
						if(count>0){
							success++;
						}else{
							error++;
						}
					}else{
					     ac.setScore(score);
					     ac.setTerm(term);
						int count=achievementService.updateAchievement(ac);
						if(count>0){
							success++;
						}else{
							error++;
						}
					}
					map.put("success", success);
					map.put("error", error);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return map;
	}
	@RequestMapping("importExpandQuality")
	@SkipSecurityCheck
	@ResponseBody
	public Map importExpandQuality(HttpServletRequest request, ModelMap modelMap) throws FileUploadException{
		map = new HashMap();
		String savePath=request.getSession().getServletContext().getRealPath("upload");
		String tempPath=request.getSession().getServletContext().getRealPath("upload1");
		String fe=uploadFile(request);
		String fileName=fe.substring(1, fe.length()-1);
		logger.info("get fileName="+fileName);
		if("".equals(fileName)){
			map.put("upload", "filed");
		}else{
			File f =new File(savePath,fileName);
			try {
				List<List<Object>> lists=readExcel(f);
				int i=0,success=0,error=0;
				for(List<Object> list:lists){
					if(i++==0) continue;//表头不取
					if(list==null||list.size()==0) break;//读取到空结束
					Student stu = studentService.getStudentByStudentNumber(list.get(1).toString().replace(".00", ""));
					Classes clazz=classesService.getClassByName(list.get(0).toString());
					String score=list.get(3).toString().replace(".00", "");
					String score1=list.get(4).toString().replace(".00", "");
					String score2=list.get(5).toString().replace(".00", "");
					String score3=list.get(6).toString().replace(".00", "");
					logger.info("get stu ="+stu.getName() +",class="+clazz.getName()+",score="+score
							+",score1="+score1+",score2="+score2+",score3="+score3);
					ExpandQuality eq=expandQualityService.getExpandQualityByStduent(stu.getId());
					if(eq==null){
						ExpandQuality  eql =new ExpandQuality();
						eql.setClassId(clazz.getId());
                        eql.setStudentId(stu.getId());
                        eql.setInnovationCreativity(score);
                        eql.setPracticalAbility(score1);
                        eql.setManagementAbility(score2);
                        eql.setSportsAchievement(score3);
						String totalScore =String.valueOf(Integer.valueOf(score)+Integer.valueOf(score1)+Integer.valueOf(score2)+Integer.valueOf(score3));
						eql.setTotalScore(totalScore);
						logger.info("get totalScore="+totalScore);
						int count=expandQualityService.saveExpandQuality(eql);
						if(count>0){
							success++;
						}else{
							error++;
						}
					}else{
				         eq.setInnovationCreativity(score);
	                     eq.setPracticalAbility(score1);
	                     eq.setManagementAbility(score2);
	                     eq.setSportsAchievement(score3);
					     String totalScore =String.valueOf(Integer.valueOf(score)+Integer.valueOf(score1)+Integer.valueOf(score2)+Integer.valueOf(score3));
					     eq.setTotalScore(totalScore);
						int count=expandQualityService.updateExpandQuality(eq);
						if(count>0){
							success++;
						}else{
							error++;
						}
					}
					map.put("success", success);
					map.put("error", error);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return map;
	}
    
	
	
	public String uploadFile(HttpServletRequest request) throws FileUploadException{
		
		String savePath=request.getSession().getServletContext().getRealPath("upload");
		String tempPath=request.getSession().getServletContext().getRealPath("upload1");
		logger.info("get savePath="+savePath+",tempPath="+tempPath);
		List<String> path =new ArrayList<>();
		
		//创建文件夹
		File dirFile =new File(savePath);
		if(!dirFile.exists()){
			dirFile.mkdirs();
		}
		
		//创建临时文件夹
		File dirTempFile =new File(tempPath);
		if(!dirTempFile.exists()){
			dirTempFile.mkdirs();
		}
		
		DiskFileItemFactory factory= new DiskFileItemFactory();
		factory.setSizeThreshold(20*1024*1024*2);//设定使用内存超过5M时，将产生临时文件并存储于临时目录中。
		factory.setRepository(new File(tempPath));//设定存储临时文件的目录。
		ServletFileUpload upload =new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
		
		try {
			request.setCharacterEncoding("utf-8");
			List<?> items = upload.parseRequest(request);
			logger.info(items.size());
			Iterator<?> itr =items.iterator();
			
			while (itr.hasNext()){
				FileItem item = (FileItem) itr.next();
				if(!item.isFormField()){
					try {
					String fileName = item.getName();
					if(fileName.indexOf("+")>=0){
						fileName.replaceAll("\\+", "_");
					}
					File uploadedFile = new File(savePath,fileName);
				    OutputStream os = new FileOutputStream(uploadedFile);
				    InputStream is =item.getInputStream();
				    byte buf[] =new byte[1024];
				    int length =0;
				    while((length=is.read(buf))>0){
				    	os.write(buf, 0, length);
				    }
				    os.flush();
				    os.close();
				    is.close();
				    path.add(fileName);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		    String allPath = StringUtils.join(path);
		    path.clear();
		    return allPath;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	public List<List<Object>> readExcel(File file) throws IOException{
		String fileName =file.getName();
		String extension =fileName.lastIndexOf(".")==-1?"":fileName.substring(fileName.lastIndexOf(".")+1);
		if("xls".equals(extension)){
			return read2003Excel(file);
		}else if("xlsx".equals(extension)){
			return read2007Excel(file);
		}else{
			throw new IOException("不支持的Excel类型！");
		}
	}

	private List<List<Object>> read2007Excel(File file) throws FileNotFoundException, IOException {
		   List<List<Object>> list = new LinkedList<List<Object>>();
	        // 构造 XSSFWorkbook 对象，strPath 传入文件路径
	        XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file));
	        // 读取第一章表格内容
	        XSSFSheet sheet = xwb.getSheetAt(0);
	        Object value = null;
	        XSSFRow row = null;
	        XSSFCell cell = null;
	        int counter = 0;
	        for (int i = sheet.getFirstRowNum(); counter < sheet
	                .getPhysicalNumberOfRows(); i++) {
	            row = sheet.getRow(i);
	            if (row == null) {
	                continue;
	            } else {
	                counter++;
	            }
	            List<Object> linked = new LinkedList<Object>();
	            for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
	                cell = row.getCell(j);
	                if (cell == null) {
	                    continue;
	                }
	                DecimalFormat df = new DecimalFormat("0");// 格式化 number String
	                                                            // 字符
	                SimpleDateFormat sdf = new SimpleDateFormat(
	                        "yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
	                DecimalFormat nf = new DecimalFormat("0.00");// 格式化数字
	                switch (cell.getCellType()) {
	                case XSSFCell.CELL_TYPE_STRING:
	                    System.out.println(i + "行" + j + " 列 is String type");
	                    value = cell.getStringCellValue();
	                    break;
	                case XSSFCell.CELL_TYPE_NUMERIC:
	                /*  System.out.println(i + "行" + j
	                            + " 列 is Number type ; DateFormt:"
	                            + cell.getCellStyle().getDataFormatString());*/
	                    if ("@".equals(cell.getCellStyle().getDataFormatString())) {
	                        value = df.format(cell.getNumericCellValue());
	                    } else if ("General".equals(cell.getCellStyle()
	                            .getDataFormatString())) {
	                        value = nf.format(cell.getNumericCellValue());
	                    } else {
	                        value = sdf.format(HSSFDateUtil.getJavaDate(cell
	                                .getNumericCellValue()));
	                    }
	                    break;
	                case XSSFCell.CELL_TYPE_BOOLEAN:
	            //      System.out.println(i + "行" + j + " 列 is Boolean type");
	                    value = cell.getBooleanCellValue();
	                    break;
	                case XSSFCell.CELL_TYPE_BLANK:
	                //  System.out.println(i + "行" + j + " 列 is Blank type");
	                    value = "";
	                    break;
	                default:
	                //  System.out.println(i + "行" + j + " 列 is default type");
	                    value = cell.toString();
	                }
	                if (value == null || "".equals(value)) {
	                    continue;
	                }
	                linked.add(value);
	            }
	            list.add(linked);
	        }
	        return list;
	}

	private List<List<Object>> read2003Excel(File file) throws FileNotFoundException, IOException {
	     List<List<Object>> list = new LinkedList<List<Object>>();
	        HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));
	        HSSFSheet sheet = hwb.getSheetAt(0);
	        Object value = null;
	        HSSFRow row = null;
	        HSSFCell cell = null;
	        int counter = 0;
	        for (int i = sheet.getFirstRowNum(); counter < sheet
	                .getPhysicalNumberOfRows(); i++) {
	            row = sheet.getRow(i);
	            if (row == null) {
	                continue;
	            } else {
	                counter++;
	            }
	            List<Object> linked = new LinkedList<Object>();
	            for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
	                cell = row.getCell(j);
	                if (cell == null) {
	                    continue;
	                }
	                DecimalFormat df = new DecimalFormat("0");// 格式化 number String
	                                                            // 字符
	                SimpleDateFormat sdf = new SimpleDateFormat(
	                        "yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
	                DecimalFormat nf = new DecimalFormat("0.00");// 格式化数字
	                switch (cell.getCellType()) {
	                case XSSFCell.CELL_TYPE_STRING:
	                //  System.out.println(i + "行" + j + " 列 is String type");
	                    value = cell.getStringCellValue();
	                    break;
	                case XSSFCell.CELL_TYPE_NUMERIC:
	                    /*System.out.println(i + "行" + j
	                            + " 列 is Number type ; DateFormt:"
	                            + cell.getCellStyle().getDataFormatString());*/
	                    if ("@".equals(cell.getCellStyle().getDataFormatString())) {
	                        value = df.format(cell.getNumericCellValue());
	                    } else if ("General".equals(cell.getCellStyle()
	                            .getDataFormatString())) {
	                        value = nf.format(cell.getNumericCellValue());
	                    } else {
	                        value = sdf.format(HSSFDateUtil.getJavaDate(cell
	                                .getNumericCellValue()));
	                    }
	                    break;
	                case XSSFCell.CELL_TYPE_BOOLEAN:
	                //  System.out.println(i + "行" + j + " 列 is Boolean type");
	                    value = cell.getBooleanCellValue();
	                    break;
	                case XSSFCell.CELL_TYPE_BLANK:
	                //  System.out.println(i + "行" + j + " 列 is Blank type");
	                    value = "";
	                    break;
	                default:
	                //  System.out.println(i + "行" + j + " 列 is default type");
	                    value = cell.toString();
	                }
	                if (value == null || "".equals(value)) {
	                    continue;
	                }
	                linked.add(value);
	            }
	            list.add(linked);
	        }
	        return list;
	}
}
